package com.appspot.urlheap.servlets;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.urlheap.data.Item;
import com.appspot.urlheap.data.PMF;

public class RandomServlet extends BaseServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
    		String query = "select from " + Item.class.getName() + " where user == '" + getUser().getEmail() + "'";
    	    List<Item> items = (List<Item>) pm.newQuery(query).execute();
    	    long rnd = Math.round(Math.random() * (items.size() - 1));
    	    Item item = items.get(Long.valueOf(rnd).intValue());
    	    resp.sendRedirect(item.getUrl().toString());
    	    pm.deletePersistent(item);
		} finally {
			pm.close();
		}
	}
}
